package com.formula.distribution.lock.core;

import com.formula.distribution.lock.annotation.Lock;
import com.formula.distribution.lock.lock.LockFactory;
import com.formula.distribution.lock.lock.LockInterface;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author:bo
 * @email:
 * @date 2018/12/26
 * @introduce
 **/
@Aspect
@Component
public class LockAspect {


    @Autowired
    private LockFactory lockFactory;


    @Around(value = "@annotation(lock)")
    public Object around(ProceedingJoinPoint point, Lock lock) throws Throwable {


        LockInterface lockInterface = lockFactory.getLock(point, lock);
        boolean currentThreadLock = false;

        try {
            currentThreadLock = lockInterface.acquire();
            return point.proceed();
        } finally {
            if (currentThreadLock) {
                lockInterface.release();
            }
        }


    }

}
